import os
from django.conf import settings
from django.shortcuts import render, HttpResponse
from app01 import models


def upload_list(request):
    """上传文件"""
    if request.method == 'GET':
        return render(request, 'upload_list.html')
    # 请求体中的数据 - 'username': ['2039216364@qq.com']
    print(request.POST)
    # 请求发送过来的文件 - form中添加属性 enctype="multipart/form-data"
    # {'avatar': [<InMemoryUploadedFile: vsBACK.png (image/png)>]}
    print(request.FILES)

    file_obj = request.FILES.get('avatar')
    # 获取文件名
    print(file_obj.name)

    f = open(file_obj.name, mode='wb')
    for chunk in file_obj.chunks():
        f.write(chunk)
    f.close()

    return HttpResponse("提交成功!")


from django import forms
from app01.utils.bootstrap import BootStrapForm, BootStrapModelForm


class UpForm(BootStrapForm):
    bootstrap_exclude_fields = ['img']

    name = forms.CharField(label='姓名')
    age = forms.IntegerField(label='年龄')
    img = forms.FileField(label='头像')


def upload_form(request):
    title = 'Form上传'
    if request.method == 'GET':
        form = UpForm()
        return render(request, 'upload_form.html', {'form': form, 'title': title})
    form = UpForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        print(form.cleaned_data)
        # 读取到内容, 自己处理每个字段的数据
        # 1. 读取图片内容, 写到文件夹中, 获取路径
        img_obj = form.cleaned_data.get('img')
        # file_path = f'app01/static/img/{img_obj.name}'

        # media_path = os.path.join(settings.MEDIA_ROOT, img_obj.name)
        media_path = os.path.join('media', img_obj.name)

        f = open(media_path, mode='wb')
        for chunk in img_obj.chunks():
            f.write(chunk)
        f.close()
        # 2. 将图片文件路径写入数据库
        models.Boss.objects.create(
            name=form.cleaned_data['name'],
            age=form.cleaned_data['age'],
            img=media_path
        )
        # return render(request, 'tx1.html', {'img': media_path})
        return HttpResponse('上传成功')
    return render(request, 'upload_form.html', {'form': form, 'title': title})


class UpModelForm(BootStrapModelForm):
    bootstrap_exclude_fields = ['img']

    class Meta:
        model = models.City
        fields = '__all__'


def upload_model_form(request):
    """上传文件和数据 (基于ModelForm)"""
    title = 'ModelForm上传'
    if request.method == 'GET':
        form = UpModelForm()
        return render(request, 'upload_form.html', {'form': form, 'title': title})

    form = UpModelForm(data=request.POST, files=request.FILES)
    if form.is_valid():
        # 对于文件自动保存的指定路径(upload_to='savePath')
        # 字段 + 上传路径 写入数据库
        form.save()
        return HttpResponse("上传成功")
    return render(request, 'upload_form.html', {'form': form, 'title': title})
